import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 文章id
    artId: 0,
    goodsCar: {
      goodCar: []
    }
  },

  mutations: {
    // 接受newsDetail传入的文章id
    getArtId (state, id) {
      state.artId = id
    },
    addGoodNum (state, params) {
      console.log(params, '---------------params')
      const car = state.goodsCar.goodCar
      if (params.id) {
        car.forEach(item => {
          if (item.id === params.id) {
            item.num = parseInt(item.num) + parseInt(params.num)
          }
        })
        const is = car.some(item => item.id === params.id)
        if (!is) {
          car.push(params)
        }
      }
      window.localStorage.setItem('cartsId', JSON.stringify(state.goodsCar))
    },
    changeCartsData (state, obj) {
      state.goodsCar = JSON.parse(window.localStorage.getItem('cartsId'))
      state.goodsCar.goodCar.forEach(item => {
        if (item.id === obj.id) {
          item.num = obj.num
        }
      })
      window.localStorage.setItem('cartsId', JSON.stringify(state.goodsCar))
    },
    removeCartsGoods (state, id) {
      state.goodsCar = JSON.parse(window.localStorage.getItem('cartsId'))
      state.goodsCar.goodCar.forEach((item, index) => {
        if (item.id === id) {
          state.goodsCar.goodCar.splice(index, 1)
        }
      })
      window.localStorage.setItem('cartsId', JSON.stringify(state.goodsCar))
    }
  },
  actions: {
  },
  modules: {
  }

})
